# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=waf
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.25
pkgrel=2
pkgdesc="General-purpose build system modelled after Scons (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
license=('spdx:BSD-3-Clause')
url="https://waf.io/"
makedepends=("${MINGW_PACKAGE_PREFIX}-cc")
depends=("${MINGW_PACKAGE_PREFIX}-python")
options=('!emptydirs')
source=("https://waf.io/${_realname}-${pkgver}.tar.bz2"{,.asc}
        "0001-timeout-at-wait-after-kill.patch")
validpgpkeys=('8AF22DE5A06822E3474F3C7049B4C67C05277AAA'
              '0B3972B2D9E32EAB423D2E0F22BE0C62FFBFA548') # "Thomas Nagy <tnagy@waf.io>"
sha256sums=('66cff7beed0e77db874e9232cc08874abb3e866c7f0f1f34ba2f959fde44fdd4'
            'SKIP'
            '45239bbe8a12f6a0991ca9f4c6ddffb1b9f641199b6c5ab0d9abe038873f2b19')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Np1 -i "${srcdir}/$_patch"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  # Extract license
  head -n 30 waf-light | tail -n 25 > LICENSE

  apply_patch_with_msg \
    0001-timeout-at-wait-after-kill.patch
}

build() {
  cd "${srcdir}/${_realname}-${pkgver}"
  plain "Configure ..."
  ${MINGW_PREFIX}/bin/python ./waf-light configure --prefix=${MINGW_PREFIX}
  plain "Make waf ..."
  ${MINGW_PREFIX}/bin/python ./waf-light --make-waf
}

package() {
  cd "${srcdir}/${_realname}-${pkgver}"

  prelude=$(cat <<'EOF'
	import waflib.Tools.compiler_c, waflib.Tools.compiler_cxx
	waflib.Tools.compiler_c.c_compiler['win32'] = ['gcc', 'clang', 'msvc']
	waflib.Tools.compiler_cxx.cxx_compiler['win32'] = ['g++', 'clang++', 'msvc']
EOF
  )

  ${MINGW_PREFIX}/bin/python ./waf-light install -f --destdir="${pkgdir}" \
    --prelude="${prelude}" \
    --tools='compat,compat15,ocaml,go,cython,scala,erlang,cuda,gcj,boost,pep8,eclipse,unity,clang_compilation_database'

  install -Dm755 waf "${pkgdir}${MINGW_PREFIX}/bin/waf"
  install -Dm755 waf.bat "${pkgdir}${MINGW_PREFIX}/bin/waf.bat"

  # Force the generation of .waf.admin files
  cd "${srcdir}/${_realname}-${pkgver}/demos/c"
  CC_NAME=${CC} CC="${MINGW_PREFIX}/bin/${CC}.exe" \
  CXX_NAME=${CXX} CXX="${MINGW_PREFIX}/bin/${CXX}.exe" \
  "${pkgdir}${MINGW_PREFIX}/bin/waf" configure build

  # Fix weird directory placement (FS#38216, FS#38300)
  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib/waf"
  mv "${pkgdir}${MINGW_PREFIX}/bin/waf3-${pkgver}-"* "${pkgdir}${MINGW_PREFIX}/lib/waf/"
  sed -s "s|INSTALL=''|INSTALL='${MINGW_PREFIX}/lib/waf'|g" -i "${pkgdir}${MINGW_PREFIX}/bin/waf"

  cd "${srcdir}/${_realname}-${pkgver}"
  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
